package gw.com.android.upgrade;

import android.os.Bundle;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import gw.com.android.app.AppMain;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.util.DeviceUtil;

/**
 * 版本升级检测类
 *
 * @author reeta
 */
public class AppVersionCheck {
    /**
     * 当前是否正在检测应用版本信息
     */
    private static boolean isCheckingAppVersionNow = false;
    /**
     * 检测是自动检测还是用户手动检测升级版本
     */
    private boolean isUserCheckAppVersion = false;
    /**
     * 版本升级回调函数
     */
    private UpgradeAction upGradeAction;
    /**
     * 版本状态
     */
    public VERSION_CHECK_STATUS versionCheckStatus = VERSION_CHECK_STATUS.FORCEUP_UPGRADE;

    public enum VERSION_CHECK_STATUS {
        FORCEUP_UPGRADE, // 检测有新版本，强制升级
        NORMAL_UPGRADE, // 检测有新版本，手动升级
        NO_VERSION_UPGRADE // 检测无版本更新
    }

    private Disposable rxBusRegister;
    /**
     * 系统更新对象
     */
    private String responseResult = "";
    /**
     * 当前版本是否为最新版本
     */
    public boolean isUpdate;

    /**
     * 版本升级回调接口
     *
     * @author Administrator
     */
    public interface UpgradeAction {
        /**
         * @param status
         * @param url
         * @param versionInfo
         */
        void versionCheckSuccess(VERSION_CHECK_STATUS status, String url, String versionInfo);// 版本检测成功
    }

    public AppVersionCheck() {
        rxBusRegister = RxBus.getInstance().register(GTSConst.REPLY_HTTP_UPDATE + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onResultPresenter(bundle);
                    }
                });
    }

    protected void onResultPresenter(Bundle bundle) {
        int iValue = bundle.getInt("iValue");
        responseResult = bundle.getString("strObject");
        if (iValue != 0 || responseResult == null || "".equals(responseResult) || !responseResult.startsWith("{") || !responseResult.endsWith("}")) {
            isCheckingAppVersionNow = false;
            if (isUserCheckAppVersion) {
                ServerConnnectUtil.instance().connnectTimeOutToast(R.string.app_upgrade_error);
            }
            RxBus.getInstance().post(GTSConst.REPLY_POP_ADS_AFTER_UGPRADE, 0);
            return;
        }
        Logger.i("版本升级接收到回调!!!!!! ");
        try {
            JSONObject versionInfo = new JSONObject(responseResult).optJSONObject("data");
            String newVersion = versionInfo.optString("version").replace(".", "");
            String down_url = versionInfo.optString("url");

            int versionCode = -1;
            try {
                versionCode = Integer.parseInt(newVersion);
            } catch (NumberFormatException ignore) {
            }
            if (DeviceUtil.instance().appVersionCode(AppMain.getApp()) < versionCode) {
                isUpdate = true;
                // 是否强制更新
                if (versionInfo.optString("isForce").equals("0")) { // 登录页面不提示更新
                    if (isUserCheckAppVersion) {
                        versionCheckStatus = VERSION_CHECK_STATUS.NORMAL_UPGRADE;
                    } else {
                        //							isUpdate = true;
                        versionCheckStatus = VERSION_CHECK_STATUS.NO_VERSION_UPGRADE;
                    }
                    onAppVersionCheckFinished(down_url, versionInfo.optString("comment").replaceAll("<p>", "").replaceAll("</p>", ""));
                } else if (versionInfo.getString("isForce").equals("1")) {// 提示更新
                    versionCheckStatus = VERSION_CHECK_STATUS.NORMAL_UPGRADE;
                } else if (versionInfo.getString("isForce").equals("2")) {// 强制更新
                    versionCheckStatus = VERSION_CHECK_STATUS.FORCEUP_UPGRADE;
                }
            } else {
                isUpdate = false;
                versionCheckStatus = VERSION_CHECK_STATUS.NO_VERSION_UPGRADE;
                if (isUserCheckAppVersion) {
                    ServerConnnectUtil.instance().connnectTimeOutToast(R.string.app_upgrade_no_version_update);
                }
            }
            onAppVersionCheckFinished(down_url, versionInfo.optString("comment").replaceAll("<p>", "").replaceAll("</p>", ""));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户手动点更新
     */
    public void checkAppVersionByUser(UpgradeAction action) {
        if (isCheckingAppVersionNow) {
            ServerConnnectUtil.instance().connnectTimeOutToast(R.string.app_upgrade_checking_now);
            return;
        }

        isUserCheckAppVersion = true;
        upGradeAction = action;
        executeAppVersionCheck();
    }

    /**
     * 程序自动更新
     */
    public void autoCheckAppVersion(UpgradeAction action) {
        /* 如果正在进行版本检测，那就不用操心了 */
        if (isCheckingAppVersionNow) {
            return;
        }
        isUserCheckAppVersion = false;
        upGradeAction = action;
        executeAppVersionCheck();
    }

    /**
     * 执行应用程序版本检测操作
     */
    private void executeAppVersionCheck() {
        isCheckingAppVersionNow = true;
        AppTerminal.instance().getUpdateVersion();
    }

    /**
     * 返回版本是否正在检测的标识
     *
     * @return
     */
    public boolean hasCheckingVersion() {
        return isCheckingAppVersionNow;
    }

    /**
     * 应用程序版本检测结束后一定调用的方法，做新版本检测的清理工作
     */
    public void onAppVersionCheckFinished(String url, String versionInfo) {
        isCheckingAppVersionNow = false;
        if (null != upGradeAction) {
            upGradeAction.versionCheckSuccess(versionCheckStatus, url, versionInfo);
        }
    }

}
